
#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>


void serialize()
{
    // 序列化
    std::string name = "张三";
    int age = 18;
    float score[] = { 77.5f, 22.6f, 88.9f };
    
    Json::Value val;
    val["姓名"] = name;
    val["年龄"] = age;
    for (int i = 0; i < 3; i++)
    {
        val["成绩"].append(score[i]);
    }

    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    
    std::stringstream ss;
    int ret = sw->write(val, &ss);
    if (ret != 0)
    {
        std::cout << "write failed!" << std::endl;
        return;
    }
    std::cout << ss.str() << std::endl;
}


void Deserialize(const std::string& str)
{
    // 反序列化 
    Json::Value val;
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    
    std::string err;
    bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &val, &err);
    if (ret == false)
    {
        std::cout << "Parse failed!" << std::endl;
        std::cout << err << std::endl;
        return;
    }

    std::cout << "姓名：" << val["姓名"].asString() << std::endl;
    std::cout << "年龄：" << val["年龄"].asInt() << std::endl;
    std::cout << "成绩：[ ";

    int size = val["成绩"].size();
    for (int i = 0; i < size; ++i)
    {
        if (i < size - 1) std::cout << val["成绩"][i].asFloat() << ", ";
        else std::cout << val["成绩"][i].asFloat() << " ]" << std::endl;
    }
}


int main()
{
    // serialize();
    std::string str = R"({"姓名":"小红", "年龄":22, "成绩":[10.5, 22.6, 77.9]})";
    Deserialize(str);
    return 0;
}


